package ui;

import java.text.NumberFormat;
import java.text.ParseException;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.InternationalFormatter;
import javax.swing.text.MaskFormatter;

import dao.LotteryTicketDAOJDBC;
import dao.UserDAOJDBC;
import information.User;
import tool.RandomString;

import java.util.Random;
import javax.swing.* ;
/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
 */

/**
 *
 * @author 26860
 */
public class BuyMain extends javax.swing.JFrame {
//	class IntFilter extends DocumentFilter {
//		//重载insertString方法
//		    public void insertString(FilterBypass fb, int offset, String string,
//		            AttributeSet attr) throws BadLocationException {
//		        StringBuilder builder = new StringBuilder(string);
//		        for (int i = builder.length() - 1; i >= 0; i--) {
//		            int cp = builder.codePointAt(i);
//		            if (!Character.isDigit(cp) && cp != '-') {
//		                builder.deleteCharAt(i);
//		                if (Character.isSupplementaryCodePoint(cp)) {
//		                    i--;
//		                    builder.deleteCharAt(i);
//		                }
//		            }
//		        }
//		        super.insertString(fb, offset, builder.toString(), attr);
//		    }
//		//重载replace方法
//		    public void replace(FilterBypass fb, int offset, int length, String string,
//		            AttributeSet attr) throws BadLocationException {
//		        if (string != null) {
//		            StringBuilder builder = new StringBuilder(string);
//		            for (int i = builder.length() - 1; i >= 0; i--) {
//		                int cp = builder.codePointAt(i);
//		                if (!Character.isDigit(cp) && cp != '-') {
//		                    builder.deleteCharAt(i);
//		                    if (Character.isSupplementaryCodePoint(cp)) {
//		                        i--;
//		                        builder.deleteCharAt(i);
//		                    }
//		                }
//		            }
//		            string = builder.toString();
//		        }
//		        super.replace(fb, offset, length, string, attr);
//		    }
//		}
		

    User userMessage=new User();
    public BuyMain(User user) {
        initComponents(user);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents(User user) {
    	userMessage=user;
    	
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        rollButton = new javax.swing.JButton();
        okButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        
       // jFormattedTextField1 = new javax.swing.JFormattedTextField(NumberFormat.getIntegerInstance());
        MaskFormatter formatter = null;
		try {
			formatter = new MaskFormatter("##");
			formatter.setValidCharacters("1234567890");
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		formatter.setPlaceholderCharacter('0');
		jFormattedTextField1 = new javax.swing.JFormattedTextField(formatter);
		jFormattedTextField2 = new javax.swing.JFormattedTextField(formatter);
		jFormattedTextField3 = new javax.swing.JFormattedTextField(formatter);
		jFormattedTextField4 = new javax.swing.JFormattedTextField(formatter);
		jFormattedTextField5 = new javax.swing.JFormattedTextField(formatter);
		jFormattedTextField6 = new javax.swing.JFormattedTextField(formatter);

        jFormattedTextField1.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 24));
        jFormattedTextField2.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 24));
        jFormattedTextField3.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 24));
        jFormattedTextField4.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 24));
        jFormattedTextField5.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 24));
        jFormattedTextField6.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 24));
       

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 18)); // NOI18N
        jLabel1.setText("彩票选号");

        jLabel2.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 14)); // NOI18N

        rollButton.setText("随机");
        rollButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rollButtonActionPerformed(evt);
            }
        });

        okButton.setText("确认");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        backButton.setText("返回");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });
        
        LotteryTicketDAOJDBC dao =new LotteryTicketDAOJDBC();
        jLabel3.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N
        int num=dao.getNewLotteryIssue()+1;
        jLabel3.setText("这是第"+num+"期彩票");

        jLabel4.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 51, 51));
        if(dao.checkUserBuyLottery(user.getUserName())) {
        	jLabel4.setText("您本次已经购买，不能再次购买！");
        }else {
        	jLabel4.setText("您本次还未购买");
        }
        

        jFormattedTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField1ActionPerformed(evt);
            }
        });

        jFormattedTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField2ActionPerformed(evt);
            }
        });

        jFormattedTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField3ActionPerformed(evt);
            }
        });

        jFormattedTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField4ActionPerformed(evt);
            }
        });

        jFormattedTextField5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField5ActionPerformed(evt);
            }
        });

        jFormattedTextField6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField6ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(175, 175, 175)
                        .addComponent(jLabel1)))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(17, 17, 17)
                            .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGap(64, 64, 64)
                            .addComponent(rollButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(33, 33, 33)
                            .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel4)
                        .addComponent(jLabel3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jFormattedTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jFormattedTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(36, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rollButton)
                    .addComponent(okButton)
                    .addComponent(backButton))
                .addGap(36, 36, 36)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addContainerGap(50, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void jFormattedTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        // TODO add your handling code here:

        
    }                                                    

    private void jFormattedTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        // TODO add your handling code here:
    }                                                    

    private void jFormattedTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        // TODO add your handling code here:
    }                                                    

    private void jFormattedTextField4ActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        // TODO add your handling code here:
    }                                                    

    private void jFormattedTextField5ActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        // TODO add your handling code here:
    }                                                    

    private void jFormattedTextField6ActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        // TODO add your handling code here:
    }                                                    

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        UserMain user=new UserMain(userMessage);
        user.setVisible(true);
        this.setVisible(false);
    }                                          

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt)   {                                         
        StringBuilder sb=new StringBuilder();
        sb.append(jFormattedTextField1.getText());
        sb.append(jFormattedTextField2.getText());
        sb.append(jFormattedTextField3.getText());
        sb.append(jFormattedTextField4.getText());
        sb.append(jFormattedTextField5.getText());
        sb.append(jFormattedTextField6.getText());
        String lotteryNumber=sb.toString();

        LotteryTicketDAOJDBC daoTicket=new LotteryTicketDAOJDBC();
        UserDAOJDBC daoUser=new UserDAOJDBC();
        if(userMessage.getMoney()<10) {
    		JOptionPane.showMessageDialog(null, "您账户余额不足，现在余额为："+userMessage.getMoney()+"元，请充值", "错误！", JOptionPane.ERROR_MESSAGE);
        }else {
if(daoTicket.checkUserBuyLottery(userMessage.getUserName())) {
        	JOptionPane.showMessageDialog(null, "您已经购买过本次彩票，请耐心等待开奖", "错误！", JOptionPane.ERROR_MESSAGE);	
        }else {
        try {
			daoUser.changeMoney(userMessage.getUserName(), -10);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}	
        daoTicket.buyLottery(userMessage.getUserName(), lotteryNumber);
        if(daoTicket.checkUserBuyLottery(userMessage.getUserName())) {
        	JOptionPane.showMessageDialog(null, "购买成功,您购买的号码为"+lotteryNumber);
        }else {
        	JOptionPane.showMessageDialog(null, "您没有购买成功，请重试或联系管理员", "错误！", JOptionPane.ERROR_MESSAGE);	
        }}}
    }                                        

    private void rollButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	RandomString r=new RandomString();
    	String one=r.getRandomString();
    	String two=r.getRandomString();
    	String three=r.getRandomString();
    	String four=r.getRandomString();
    	String five=r.getRandomString();
    	String six=r.getRandomString();
    	

        jFormattedTextField1.setText(one);
        jFormattedTextField2.setText(two);
        jFormattedTextField3.setText(three);
        jFormattedTextField4.setText(four);
        jFormattedTextField5.setText(five);
        jFormattedTextField6.setText(six);//实现随机选号
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BuyMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BuyMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BuyMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BuyMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            	User userTest=new User("guohaobing",100);
                new BuyMain(userTest).setVisible(true);
                
            }
        });
        
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton backButton;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JFormattedTextField jFormattedTextField2;
    private javax.swing.JFormattedTextField jFormattedTextField3;
    private javax.swing.JFormattedTextField jFormattedTextField4;
    private javax.swing.JFormattedTextField jFormattedTextField5;
    private javax.swing.JFormattedTextField jFormattedTextField6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton okButton;
    private javax.swing.JButton rollButton;
    // End of variables declaration                   
}
